<template>
  <el-dialog
    :title="title"
    :visible.sync="innerVisible"
    width="600px"
    @close="handleCancel"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="180px"
    >
      <!-- <el-form-item label="当前推进节点">
        <el-select
          placeholder=""
          @change="handleChange"
          v-model="form.stage"
        >
          <el-option
            v-for="item in sectionNodeOptions"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="标段名称" v-if="sectionName">
        <el-input
          v-model="sectionName"
          type="textarea"
          disabled
        />
      </el-form-item>

      <el-form-item
        prop="stageRemark"
        label="当前进展(形象进度描述)"
      >
        <el-input
          v-model="form.stageRemark"
          placeholder="请输入"
          type="textarea"
        />
      </el-form-item>

      <el-form-item label="是否存在困难">
        <el-radio-group v-model="form.hasProblem">
          <el-radio label="是"></el-radio>
          <el-radio label="否"></el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="问题描述">
        <el-input
          v-model="form.problemDescription"
          placeholder="请输入"
          type="textarea"
        />
      </el-form-item>

      <el-form-item label="效果图">
        <el-image
          v-for="item in effectList"
          :key="item.filePath"
          :src="item.src"
          :preview-src-list="effectPreviewList"
          style="
            width: 100px;
            height: 100px;
            margin-left: 8px;
          "
        ></el-image>
      </el-form-item>

      <el-form-item label="实景图">
        <el-upload
          class="upload-image"
          action=""
          list-type="picture-card"
          :auto-upload="false"
          :file-list="mergedFileList"
          :on-change="handleChangeImage"
          :on-remove="handleRemoveImage"
          multiple
          accept="image/*"
          :on-preview="handlePreview"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <span>(请按效果图顺序，上传对应的实景图)</span>
        <div
          style="
            color: #999;
            font-size: 12px;
            margin-top: 5px;
          "
        >
          当前图片数量：{{ mergedFileList.length }}
        </div>

        <el-dialog
          :visible.sync="dialogImageVisible"
          width="600px"
        >
          <img
            :src="dialogImageUrl"
            alt="预览图"
            style="width: 100%"
          />
        </el-dialog>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <!-- <el-button @click="improveNode"
        >完善节点时间</el-button
      > -->
      <el-button type="primary" @click="handleConfirm"
        >确定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { sectionNodeOptions } from '@/utils/project/data'
import { STATIC_FILE_URL } from '@/api/config.js'
export default {
  name: 'ProgressDialog',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: '填写信息'
    },
    modelValue: {
      type: Object,
      default: () => ({})
    },
    pkid: {
      type: String,
      default: ''
    },
    projectId: {
      type: String,
      default: ''
    },
    effectList: {
      type: Array
    },
    currentData: {
      type: Object
    },
    isEdit: {
      type: Boolean
    },
    realList: {
      type: Array
    },
    sectionName: {
      type: String
    }
  },
  data() {
    return {
      form: {
        stageRemark: '',
        problemDescription: '',
        hasProblem: '否'
      },
      rules: {
        stageRemark: [
          {
            required: true,
            message: '请输入当前进展',
            trigger: 'blur'
          }
        ]
      },
      options: [
        {
          label: '选项1',
          value: 1
        }
      ],
      dialogImageVisible: false,
      dialogImageUrl: '',
      fileList: [],
      innerVisible: false,
      uploadFileList: [],
      effectPreviewList: []
    }
  },
  computed: {
    sectionNodeOptions() {
      return sectionNodeOptions
    },
    STATIC_FILE_URL() {
      return STATIC_FILE_URL
    },
    mergedFileList() {
      // 处理已上传的图片
      const uploaded = (this.realList || []).map(
        (item, idx) => {
          // 判断是否为已上传的图片（有pkid或fileId属性）
          if (item.pkid || item.fileId) {
            const uploadedItem = {
              name:
                item.filePath ||
                item.name ||
                `image-${idx}`,
              url: `${STATIC_FILE_URL}${item.filePath}`,
              uid: `uploaded-${idx}`,
              isUploaded: true,
              pkid: item.pkid,
              fileId: item.fileId,
              filePath: item.filePath,
              originalData: item
            }
            return uploadedItem
          } else if (item instanceof File) {
            // 处理本地File对象
            const localFileItem = {
              name: item.name,
              url: URL.createObjectURL(item),
              uid: `local-${idx}`,
              isUploaded: false,
              raw: item,
              originalData: item
            }
            return localFileItem
          } else {
            // 处理其他格式的本地文件数据
            const otherItem = {
              name: item.name || `image-${idx}`,
              url:
                item.url ||
                (item.raw
                  ? URL.createObjectURL(item.raw)
                  : ''),
              uid: `other-${idx}`,
              isUploaded: false,
              raw: item.raw || item,
              originalData: item
            }
            return otherItem
          }
        }
      )

      // 处理新上传的文件
      const newFiles = this.uploadFileList.map(
        (file, idx) => {
          const newFileItem = {
            name: file.name,
            url: URL.createObjectURL(file),
            uid: `new-${idx}`,
            raw: file,
            isUploaded: false,
            originalData: file
          }

          return newFileItem
        }
      )

      const result = [...uploaded, ...newFiles]
      return result
    }
  },
  watch: {
    visible(val) {
      this.innerVisible = val
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate()
      }
      if (!this.isEdit) {
        this.form = {
          stageRemark: '',
          problemDescription: '',
          hasProblem: '否'
        }
        this.uploadFileList = []
      }
    },
    innerVisible(val) {
      this.$emit('update:visible', val)
    },
    currentData: {
      handler(val) {
        if (val) {
          this.form = { ...val }
        }
      },
      deep: true,
      immediate: true
    },
    effectList(val) {
      if (val && val.length) {
        this.effectPreviewList = val.map((item) => item.src)
      } else {
        this.effectPreviewList = []
      }
    },
    realList: {
      handler(val) {
        // realList变化时，mergedFileList会自动重新计算
        this.$nextTick(() => {})
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    handleCancel() {
      this.$emit('update:visible', false)
      // 清理数据
      this.uploadFileList = []
    },
    improveNode() {
      this.$router.push({
        path: '/dataManagement/projectManagement/sectionManagement/add',
        query: {
          pkid: this.pkid,
          projectId: this.projectId,
          title: '编辑',
          isEdit: true
        }
      })
    },
    handleConfirm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 强制更新组件，确保计算属性重新计算
          this.$forceUpdate()

          // 使用nextTick确保更新完成后再处理数据
          this.$nextTick(() => {
            // 分离已上传的图片和新上传的文件
            const uploadedImages = this.mergedFileList
              .filter((file) => file.isUploaded)
              .map((file, index) => ({
                pkid: file.pkid,
                filePath: file.filePath || file.name,
                orderIndex: index,
                fileId: file.fileId
              }))

            // 获取新上传的文件（包括本地文件和新选择的文件）
            const newUploadFiles = this.mergedFileList
              .filter((file) => !file.isUploaded)
              .map((file) => file.raw || file.originalData)
              .filter((file) => file instanceof File)

            this.$emit(
              'confirm',
              { ...this.form },
              newUploadFiles,
              uploadedImages
            )

            this.handleCancel()
          })
        }
      })
    },
    handleChange() {},
    handleChangeImage(file) {
      if (file.raw) {
        this.uploadFileList.push(file.raw)
      }
    },
    handleRemoveImage(file) {
      if (file.isUploaded) {
        // 不直接修改realList props，而是通知父组件
        this.$emit('remove-uploaded', file)
      } else {
        // 从uploadFileList中移除新上传的文件
        const fileToRemove = file.raw || file.originalData
        const beforeCount = this.uploadFileList.length
        this.uploadFileList = this.uploadFileList.filter(
          (f) => f !== fileToRemove
        )
        const afterCount = this.uploadFileList.length
      }
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/dialog.scss';
.el-select {
  width: 320px;
}

::v-deep .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

::v-deep
  .el-upload-list--picture-card
  .el-upload-list__item {
  width: 100px;
  height: 100px;
}

.form-label {
  line-height: 0.5 !important;
}

::v-deep(.el-form-item__label) {
  white-space: normal;
  line-height: 20px !important;
}
</style>
